#include "Sqlite.h"

#include <QMessageBox>
#include <QSqlError>
//#include <QSqlQuery>


Sqlite::Sqlite()
{
    m_pDB = nullptr;
}

void Sqlite::close()
{
    if(m_pDB == nullptr)
        return;

    if(m_pDB->isValid() && m_pDB->isOpen())
    {
        m_pDB->close();
        QString dbName = m_pDB->connectionName();
        delete m_pDB;
        m_pDB = nullptr;
        QSqlDatabase::removeDatabase(dbName);
    }
}

Sqlite::~Sqlite()
{
    close();
}


bool Sqlite::connectDB(const QString &dbName, const QString &password)
{
    if(QSqlDatabase::contains(dbName))
        return true;

    //if(m_dbName == dbName)
    //    return true;

    close();
    m_pDB = new QSqlDatabase;

//#ifdef Q_OS_WIN32

    if(password.isEmpty() || !QSqlDatabase::isDriverAvailable("SQLITECIPHER"))
    {
        *m_pDB = QSqlDatabase::addDatabase("QSQLITE",dbName); //设置驱动和名字
        m_pDB->setDatabaseName(dbName);   //设置数据库名字
    }
    else
    {
        *m_pDB = QSqlDatabase::addDatabase("SQLITECIPHER",dbName); //设置驱动和名字
        //	QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE", QString("con%1").arg(dbName));
        //        db.setHostName("host");
        //        db.setDatabaseName("dbname");
        //        db.setUserName("username");
        //        db.setPassword("password");
        m_pDB->setDatabaseName(dbName);   //设置数据库名字
        m_pDB->setPassword(password);
    }

//#else
//    *m_pDB = QSqlDatabase::addDatabase("QSQLITE",dbName); //设置驱动和名字
//    m_pDB->setDatabaseName(dbName);   //设置数据库名字
//#endif

    if (!m_pDB->open())   //打开
    {
        showError(QObject::tr("Database Error"));
        return false;
    }
    //m_dbName = dbName;
    return true;
}

void Sqlite::showError(QString str)
{
    if(isValid())
        QMessageBox::critical(nullptr, str, m_pDB->lastError().text());
}

